from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from PySide6.QtWidgets import QLabel, QComboBox, QPushButton
from enums.WidgetType import WidgetType
from enums.ZhButtonType import ZhButtonType
from enums.ButtonType import ButtonType
from widgets.scriptWidgets.ScriptInput import ScriptInput
from util.Mouse import MouseUtil


class ClickPos(ScriptWidget):
    def __init__(self, widgetType, initType=None):
        super().__init__(widgetType)
        self.initType = initType

        self.labTitle = QLabel(self)
        if widgetType == WidgetType.CLICK_POS:
            self.labTitle.setText('单击:')
        elif widgetType == WidgetType.DOUBLE_CLICK_POS:
            self.labTitle.setText('双击:')

        self.labTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        # x
        self.inputX = ScriptInput(self, 'x')
        self.inputX.text = 0
        self.addWidget(self.inputX)

        # y
        self.inputY = ScriptInput(self, 'y')
        self.inputY.text = 0
        self.addWidget(self.inputY)

        # buttonType
        self.comButtonType = QComboBox(self)
        self.comButtonType.addItems(ZhButtonType.values())
        self.comButtonType.setCurrentText(ZhButtonType.values()[0])
        self.addWidget(self.comButtonType)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('选择位置')
        self.btnTrack.clicked.connect(self.startClickListener)
        self.addWidget(self.btnTrack)

    def onMouseClick(self, x, y, button, pressed):
        self.inputX.text = int(x)
        self.inputY.text = int(y)
        buttonName = button.name.upper()
        self.comButtonType.setCurrentText(ZhButtonType[buttonName].value)
        return False

    def startClickListener(self):
        MouseUtil.listenClick(self.onMouseClick)

    @property
    def data(self):
        zhType = ZhButtonType(self.comButtonType.currentText())
        buttonType = ButtonType[zhType.name].value
        return {
            "type": self.type.value,
            'x': int(self.inputX.text),
            'y': int(self.inputY.text),
            'button': buttonType,
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.setData(data)
        self.inputX.text = data['x']
        self.inputY.text = data['y']
        self.comButtonType.setCurrentText(ZhButtonType[data['button'].upper()].value)
